<script setup>
import { ref, getCurrentInstance, onMounted } from 'vue';
import { getStore, setStore } from '../services/book-store'
import { getBookSources, addBookSource, deleteBookSource } from '../services/bookService';

const { proxy } = getCurrentInstance();
const sourceUrl = ref('');
const loading = ref(false);
const loading1 = ref(false);
const bookSources = ref([]);
const errorMessage = ref('');

// 加载书源列表
const loadBookSources = () => {
  bookSources.value = getBookSources();
};

// 组件挂载时加载书源列表
onMounted(() => {
  loadBookSources();
});

// 从URL获取书源数据
const fetchSourceData = async (url) => {
  if (!(sourceUrl.value.trim() || url)) {
    proxy.$toast.warning('请输入有效的书源地址');
    return;
  }
  if(url)loading1.value = true;
  else loading.value = true;
  
  errorMessage.value = '';
  fetch('https://api.yyy001.com/api/Visits?name=TINGSHUYUEDUHX')
  try {
    // 发起请求获取书源数据
    const response = await fetch(sourceUrl.value || url);
    
    if (!response.ok) {
      throw new Error(`请求失败: ${response.status}`);
    }
    
    const data = await response.json();
    
    // 验证数据格式是否符合要求
    if (!Array.isArray(data) && !data.bookSourceUrl) {
      throw new Error('无效的书源数据格式');
    }
    
    // 处理数据
    const sources = Array.isArray(data) ? data : [data];
    
    // 添加书源
    const addedCount = addBookSource(sources);
    
    if (addedCount > 0) {
      proxy.$toast.success(`成功添加${addedCount}个书源`);
    } else {
      proxy.$toast.info('所有书源已存在，未添加新书源');
    }
    setStore('sourceUrl', sourceUrl.value || url);
    // 刷新书源列表
    loadBookSources();
    
    // 清空输入框
    sourceUrl.value = '';
    
  } catch (error) {
    console.error('获取书源失败:', error);
    errorMessage.value = error.message || '获取书源数据失败';
    proxy.$toast.error(errorMessage.value);
  } finally {
    loading1.value = false;
    loading.value = false;
  }
};

// 同步书源列表
const syncBookSources = async () => {
  let url = getStore('sourceUrl');
   await fetchSourceData(url);
  // proxy.$toast.success('书源列表已同步');
};

// 删除书源
const deleteSource = (source) => {
  const result = deleteBookSource(source.bookSourceUrl);
  if (result) {
    proxy.$toast.success(`已删除书源 "${source.bookSourceName}"`);
    // 刷新书源列表
    loadBookSources();
  } else {
    proxy.$toast.error('删除书源失败');
  }
};
</script>

<template>
  <div class="source-manager">
    <div class="source-input">
      <input 
        type="text" 
        v-model="sourceUrl" 
        placeholder="请输入书源地址" 
        @keyup.enter="()=>fetchSourceData()"
      />
      <button class="action-btn" @click="()=>fetchSourceData()" :disabled="loading">
        <span v-if="!loading">获取</span>
        <span v-else class="loading-indicator"></span>
      </button>
      <!-- <button class="action-btn sync-btn" @click="syncBookSources" :disabled="loading1" title="同步上次的书源地址">
        <span v-if="!loading1">同步</span>
        <span v-else class="loading-indicator"></span>
      </button> -->
    </div>
    
    <div v-if="errorMessage" class="error-message">
      {{ errorMessage }}
    </div>
    
    <div class="source-list">
      <h2>书源列表 ({{ bookSources.length }})</h2>
      <div class="source-table">
        <div class="source-header">
          <div class="source-cell">名称</div>
          <div class="source-cell">URL</div>
          <div class="source-cell">操作</div>
        </div>
        <div v-for="source in bookSources" :key="source.bookSourceUrl" class="source-row">
          <div class="source-cell">{{ source.bookSourceName }}</div>
          <div class="source-cell source-url">{{ source.bookSourceUrl }}</div>
          <div class="source-cell source-btn">
            <button class="delete-btn" @click="deleteSource(source)">删除</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.source-manager {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

h1 {
  margin-bottom: 15px;
  color: var(--blue);
}

h2 {
  margin: 15px 0;
  color: var(--blue);
  font-size: 16px;
}

.source-input {
  display: flex;
  margin-bottom: 15px;
}

input {
  flex: 1;
  padding: 6px 10px;
  border: 1px solid #ddd;
  border-radius: 4px 0 0 4px;
  font-size: 14px;
  background-color: #fff;
  color: #333;
  border-color: #ddd;
  height: 32px;
}

@media (prefers-color-scheme: dark) {
  input {
    background-color: #2c3e50;
    color: #ecf0f1;
    border-color: #34495e;
  }
}

.action-btn {
  padding: 6px 12px;
  background-color: var(--blue);
  color: white;
  border: none;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
  min-height: 32px;
  line-height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

button:first-of-type {
  border-radius: 0;
}

.sync-btn {
  border-radius: 0 4px 4px 0;
  background-color: #27ae60;
}

.sync-btn:hover {
  background-color: #219653;
}

button:hover {
  background-color: #3a80d2;
}

button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.loading-indicator {
  display: inline-block;
  width: 16px;
  height: 16px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  border-top-color: white;
  animation: spin 1s ease-in-out infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.error-message {
  color: #e74c3c;
  margin-bottom: 15px;
  padding: 8px;
  background-color: rgba(231, 76, 60, 0.1);
  border-radius: 4px;
  font-size: 14px;
}

.source-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 8px;
  background-color: #fff;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

@media (prefers-color-scheme: dark) {
  .source-table {
    background-color: #2c3e50;
  }
}

.source-header {
  display: flex;
  background-color: #f5f5f5;
  font-weight: bold;
  color: #333;
}

@media (prefers-color-scheme: dark) {
  .source-header {
    background-color: #34495e;
    color: #ecf0f1;
  }
}

.source-row {
  display: flex;
  border-top: 1px solid #eee;
}

@media (prefers-color-scheme: dark) {
  .source-row {
    border-top: 1px solid #34495e;
  }
}

.source-cell {
  padding: 8px 10px;
  text-align: left;
  font-size: 14px;
}

.source-header .source-cell:nth-child(1),
.source-row .source-cell:nth-child(1) {
  width: 25%;
}

.source-header .source-cell:nth-child(2),
.source-row .source-cell:nth-child(2) {
  width: 60%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.source-header .source-cell:nth-child(3),
.source-row .source-cell:nth-child(3) {
  width: 15%;
  text-align: center;
}

.source-btn{
  display: flex;
  justify-content: center;
}

.delete-btn {
  padding: 3px 8px;
  background-color: #e74c3c;
  color: white;
  border: none;
  border-radius: 3px;
  cursor: pointer;
  transition: background-color 0.3s;
  font-size: 12px;
  min-height: 24px;
  line-height: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.delete-btn:hover {
  background-color: #c0392b;
}

/* 滚动条样式 */
.source-list::-webkit-scrollbar {
  width: 6px;
}

.source-list::-webkit-scrollbar-track-piece {
  background-color: transparent;
  border-radius: 3px;
}

.source-list::-webkit-scrollbar-thumb {
  background: var(--blue);
  border-radius: 3px;
}

.source-list::-webkit-scrollbar-thumb:hover {
  background: rgba(51, 136, 255, 0.8);
}
</style>